<template>
  <div class="user-profile-container">
    <el-card class="profile-card">
      <div class="profile-header">
        <h2>个人中心</h2>
        <el-button :loading="saving" type="primary" @click="handleSave"> 保存修改</el-button>
      </div>

      <el-row :gutter="30">
        <!-- 左侧头像区域 -->
        <el-col :sm="8" :xs="24" class="avatar-column">
          <div class="avatar-uploader">
            <el-avatar :size="150" :src="form.avatar" class="user-avatar" />
            <el-upload
              :before-upload="beforeAvatarUpload"
              :http-request="() => {}"
              :show-file-list="false"
              action="#"
              class="upload-btn"
            >
              <el-button plain round type="primary">
                <el-icon>
                  <Upload />
                </el-icon>
                更换头像
              </el-button>
            </el-upload>
          </div>
        </el-col>

        <!-- 右侧表单区域 -->
        <el-col :sm="16" :xs="24">
          <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
            <el-form-item label="用户ID">
              <el-input v-model="form.userId" disabled />
            </el-form-item>

            <el-form-item label="用户名" prop="username">
              <el-input v-model="form.username" />
            </el-form-item>

            <el-form-item label="电子邮箱">
              <el-input v-model="form.email" disabled />
            </el-form-item>

            <el-form-item label="性别" prop="gender">
              <el-select v-model="form.gender" placeholder="请选择">
                <el-option label="男" value="male" />
                <el-option label="女" value="female" />
                <el-option label="其他" value="other" />
              </el-select>
            </el-form-item>

            <el-form-item label="出生日期" prop="birthdate">
              <el-date-picker v-model="form.birthdate" placeholder="选择日期" type="date" value-format="YYYY-MM-DD" />
            </el-form-item>

            <el-form-item label="所在地区" prop="region">
              <el-cascader
                v-model="selectedRegion"
                :options="regionOptions"
                clearable
                placeholder="请选择地区"
                style="width: 100%"
              />
            </el-form-item>

            <el-form-item label="音乐主页" prop="music_link">
              <el-input v-model="form.musicLink" placeholder="请输入音乐主页链接">
                <template #prepend>HTTP://</template>
              </el-input>
            </el-form-item>

            <el-form-item label="社交媒体" prop="social_media">
              <el-input v-model="form.socialMedia" placeholder="请输入社交媒体链接">
                <template #prepend>HTTP://</template>
              </el-input>
            </el-form-item>

            <el-form-item label="个人简介" prop="bio">
              <el-input v-model="form.bio" :rows="4" placeholder="介绍一下你自己..." type="textarea" />
            </el-form-item>
          </el-form>
        </el-col>
      </el-row>

      <!-- 修改密码区域 -->
      <el-collapse class="password-section">
        <el-collapse-item name="1" title="修改密码">
          <el-form ref="pwdFormRef" :model="passwordForm" :rules="pwdRules" label-width="100px">
            <el-form-item label="原密码" prop="oldPassword">
              <el-input v-model="passwordForm.oldPassword" show-password type="password" />
            </el-form-item>

            <el-form-item label="新密码" prop="newPassword">
              <el-input v-model="passwordForm.newPassword" show-password type="password" />
            </el-form-item>

            <el-form-item label="确认密码" prop="confirmPassword">
              <el-input v-model="passwordForm.confirmPassword" show-password type="password" />
            </el-form-item>

            <el-form-item>
              <el-button type="primary" @click="handleChangePassword"> 修改密码</el-button>
            </el-form-item>
          </el-form>
        </el-collapse-item>
      </el-collapse>
    </el-card>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { useUserStore } from '@/stores'
import { regionData } from 'element-china-area-data'
import { userGetBasicInfos, userUpdatePassword, userUpdateUserInfos } from '@/api/user.js'
import { Upload } from '@element-plus/icons-vue'
import { thirdPartyOssPolicy } from '@/api/thridParty.js'
import OssUploader from '@/utils/OssUploader.js'
import { useRouter } from 'vue-router'

const userStore = useUserStore()
const router = useRouter()

const selectedRegion = ref([])
const regionOptions = ref(regionData)

const form = ref({
  userId: '',
  username: '',
  email: '',
  gender: 'other',
  birthdate: '',
  bio: '',
  avatar: '',
  region: '',
  musicLink: '',
  socialMedia: ''
})

const passwordForm = ref({
  oldPassword: '',
  newPassword: '',
  confirmPassword: ''
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 2, max: 20, message: '长度在 2 到 16 个字符', trigger: 'blur' }
  ],
  music_link: [{ type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }],
  social_media: [{ type: 'url', message: '请输入有效的URL地址', trigger: 'blur' }]
}

const pwdRules = {
  oldPassword: [
    { required: true, message: '请输入原密码密码', trigger: 'blur' },
    {
      validator: (_, v, cb) =>
        /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*.])[\da-zA-Z~!@#$%^&*.]{8,}$/.test(v)
          ? cb()
          : cb(new Error('密码需8位以上且包含字母、数字、特殊符号'))
    }
  ],
  newPassword: [
    { required: true, message: '请输入新密码', trigger: 'blur' },
    {
      validator: (_, v, cb) =>
        /^(?=.*\d)(?=.*[a-zA-Z])(?=.*[~!@#$%^&*.])[\da-zA-Z~!@#$%^&*.]{8,}$/.test(v)
          ? cb()
          : cb(new Error('密码需8位以上且包含字母、数字、特殊符号'))
    }
  ],
  confirmPassword: [{ validator: validatePassword, trigger: 'blur' }]
}

function validatePassword(rule, value, callback) {
  if (value !== passwordForm.value.newPassword) {
    callback(new Error('两次输入密码不一致'))
  } else {
    callback()
  }
}

const saving = ref(false)
const formRef = ref(null)

const handleSave = async () => {
  try {
    await formRef.value.validate()
    saving.value = true
    form.value.region = selectedRegion.value[0] + '-' + selectedRegion.value[1] + '-' + selectedRegion.value[2]
    await userUpdateUserInfos({ ...form.value })
    userStore.setAvatar(form.value.avatar)
    ElMessage.success('个人信息更新成功')
  } catch (error) {
    console.error(error)
  } finally {
    saving.value = false
  }
}

// 修改密码处理
const pwdFormRef = ref(null)

const handleChangePassword = async () => {
  try {
    await pwdFormRef.value.validate()

    await ElMessageBox.confirm('确定要修改密码吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })

    await userUpdatePassword({ email: form.value.email, ...passwordForm.value })
    userStore.removeFullInfos()
    router.push('/')
    ElMessage.success('密码修改成功')
    ElMessage.warning('请重新登录')
    passwordForm.value = {
      oldPassword: '',
      newPassword: '',
      confirmPassword: ''
    }
  } catch (error) {
    if (error !== 'cancel') {
      ElMessage.error(error.message || '密码修改失败')
    }
  }
}

// oss 上传
const ossUploader = new OssUploader({
  getPolicy: thirdPartyOssPolicy
})

const handleAvatarUpload = async file => {
  try {
    const { url: avatarUrl } = await ossUploader.upload(file)

    form.value.avatar = avatarUrl
    ElMessage.success('头像更新成功')
    return true
  } catch (error) {
    ElMessage.error(`头像上传失败: ${error.message}`)
    return false
  }
}

// 修改后的上传前校验
const beforeAvatarUpload = file => {
  // 文件类型校验
  const isImage = ['image/jpeg', 'image/png', 'image/webp'].includes(file.type)
  if (!isImage) {
    ElMessage.error('仅支持 JPG/PNG/WEBP 格式!')
    return false
  }

  // 文件大小校验 (调整为5MB)
  const isLt5M = file.size / 1024 / 1024 < 5
  if (!isLt5M) {
    ElMessage.error('图片大小不能超过 5MB!')
    return false
  }

  // 触发上传流程
  return handleAvatarUpload(file)
}

onMounted(async () => {
  try {
    const response = await userGetBasicInfos(userStore.email)
    form.value = { ...response.data }
    selectedRegion.value = response.data.region.split('-')
  } catch (error) {
    console.log(error)
  }
})
</script>

<style scoped>
.user-profile-container {
  max-width: 1200px;
  margin: 20px auto;
  padding: 0 20px;
  width: 100%;
}

.profile-card {
  border-radius: 12px;
  box-shadow: 0 2px 12px rgba(0, 0, 0, 0.1);
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 30px;
}

.avatar-column {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.avatar-uploader {
  text-align: center;
}

.user-avatar {
  margin-bottom: 20px;
  border: 2px solid #eee;
}

.upload-btn {
  margin-top: 10px;
}

.password-section {
  margin-top: 30px;
}

@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    gap: 15px;
    align-items: flex-start;
  }
}
</style>
